<script setup>
import { ref, onMounted, watch } from "vue";
import {
  queryAllClazzApi,
  queryDeptApi,
  queryDeptByIdApi,
  addClazzApi,
  deleteClazzApi,
  updateClazzApi,
} from "@/api/clazz";
import { ElMessage, ElMessageBox } from "element-plus";

const clazz = ref({
  id: "",
  name: "",
  room: "",
  date: "",
  beginDate: "",
  endDate: "",
  masterId: "",
  subject: "",
  createTime: "",
  updateTime: "",
});

// 定义 学科列表
const subjectList = ref([
  { name: "java", value: 1 },
  { name: "前端", value: 2 },
  { name: "大数据", value: 3 },
  { name: "Go", value: 4 },
  { name: "嵌入式", value: 5 },
]);

// 定义 班主任数组
const masterList = ref([
  { name: "张三", id: 1},
  { name: "李四", id: 2},
  { name: "王五", id: 3},
  { name: "赵六", id: 4},
]);

// 定义 分页配置，当前页
const currentPage = ref(1);
// 定义 默认 x条/页
const pageSize = ref(10);
// 定义 总页数
const total = ref(0);

// 处理分页大小变化
const handleSizeChange = (newPageSize) => {
  pageSize.value = newPageSize;
  handleSearch();
};

// 处理页数变化
const handleCurrentChange = (updatePage) => {
  currentPage.value = updatePage;
  handleSearch();
};

// 定义 表格数据
let clazzList = ref([]);

// 定义 查询表单 的 请求参数
const searchClazz = ref({
  name: "",
  date: [],
  begin: "",
  end: "",
});

// 根据data数据更新begin和end
watch(
  () => {
    return searchClazz.value.date;
  },
  (newValue, oldValue) => {
    if (newValue.length === 2) {
      searchClazz.value.begin = newValue[0];
      searchClazz.value.end = newValue[1];
    } else {
      searchClazz.value.begin = "";
      searchClazz.value.end = "";
    }
  }
);

// 班级列表查询
const handleSearch = async () => {
  const result = await queryDeptApi(
    searchClazz.value.name,
    searchClazz.value.begin,
    searchClazz.value.end,
    currentPage.value,
    pageSize.value
  );
  if (result.code === 1) {
    clazzList.value = result.data.rows;
    total.value = result.data.total;
  }
};

// 清空查询表单
const handleClear = () => {
  searchClazz.value = {
    name: "",
    date: [],
    begin: "",
    end: "",
  };
  handleSearch();
};

// 查询所有班级
/*const queryAllClazz = async () => {
  const result = await queryAllClazzApi();
  if (result.code === 1) {
    total.value = result.data.total;
    clazzList.value = result.data.rows;
  } else {
    ElMessage.error(result.data.msg);
  }
};*/

// 钩子函数，自动运行
onMounted(async () => {
  handleSearch();
});

// 对话框 显示状态，默认false不显示
const dialogFormVisible = ref(false);
// 对话框 标题
const dialogTitle = ref("");

// 新增班级
const addClazz = () => {
  dialogTitle.value = "新增班级";
  dialogFormVisible.value = true;
};

// 保存新班级
const saveClazz = async () => {
  let result;
  if (clazz.value.id) {
    result = await updateClazzApi(clazz.value);
  } else {
    result = await addClazzApi(clazz.value);
  }
  if (result.code === 1) {
    ElMessage.success("保存成功");
    dialogFormVisible.value = false;
    handleSearch();
  } else {
    ElMessage.error(result.msg);
  }
  // 清除对话框表单内容
  clazz.value = {
    id: "",
    name: "",
    room: "",
    date: "",
    beginDate: "",
    endDate: "",
    masterId: "",
    subject: "",
    createTime: "",
    updateTime: "",
  };
  if (clazzFromRef.value) {
    clazzFromRef.value.resetFields();
  }
};

// 取消保存
const cancel = () => {
  dialogFormVisible.value = false;
  // 清除对话框表单内容
  clazz.value = {
    id: "",
    name: "",
    room: "",
    date: "",
    beginDate: "",
    endDate: "",
    masterId: "",
    subject: "",
    createTime: "",
    updateTime: "",
  };
  if (clazzFromRef.value) {
    clazzFromRef.value.resetFields();
  }
};

// 编辑
const handleEdit = async (id) => {
  // 数据回显
  const result = await queryDeptByIdApi(id);
  clazz.value = result.data;
  // 显示对话框
  dialogTitle.value = "修改班级";
  dialogFormVisible.value = true;
};

// 删除班级
const handleDelete = (id) => {
  // 确认弹窗
  ElMessageBox.confirm("请确认是否删除", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const result = await deleteClazzApi(id);
      if (result.code === 1) {
        ElMessage.success("删除成功");
        handleSearch();
      } else {
        ElMessage.error(result.msg);
      }
    })
    .catch(() => {
      ElMessage.info("取消删除");
    });
};

// 表单校验规则
// 验证规则
const clazzFromRef = ref();
const rules = ref({
  name: [
    { required: true, message: "请输入班级名称", trigger: "blur" },
    {
      min: 4,
      max: 30,
      message: "班级名称的长度应在4到30个字符之间",
      trigger: "blur",
    },
  ],
  beginDate: [{ required: true, message: "请选择开课时间", trigger: "blur" }],
  endDate: [{ required: true, message: "请选择结课时间", trigger: "blur" }],
  subject: [{ required: true, message: "请选择学科", trigger: "blur" }],
});
</script>

<template>
  <h1>班级管理</h1>
  <br />
  <!-- 表单 -->
  <!-- 班级名称 -->
  <el-form :inline="true" :model="searchClazz" class="demo-form-inline">
    <el-form-item label="班级名称">
      <el-input
        v-model="searchClazz.name"
        placeholder="请输入班级名称"
        clearable
      />
    </el-form-item>
    <!-- 选择日期 -->
    <el-form-item>
      <span class="demonstration">结课时间：</span>
      <el-date-picker
        v-model="searchClazz.date"
        type="daterange"
        value-format="YYYY-MM-DD"
        range-separator="至"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
      />
    </el-form-item>
    <!-- 查询、清空 按钮 -->
    <el-form-item>
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button @click="handleClear">清空</el-button>
    </el-form-item>
  </el-form>
  <!-- 添加班级 按钮 -->
  <el-button type="primary" plain @click="addClazz"> + 新增班级</el-button>

  <br />
  <br />
  <!-- 展示内容的表格 -->
  <el-table :data="clazzList" border style="width: 100%">
    <el-table-column type="index" label="序号" width="100" align="center" />
    <el-table-column prop="name" label="班级名称" width="150" align="center" />
    <el-table-column prop="room" label="班级教室" width="100" align="center" />
    <el-table-column
      prop="masterId"
      label="班主任"
      width="100"
      align="center"
    />
    <el-table-column
      prop="beginDate"
      label="开课时间"
      width="150"
      align="center"
    />
    <el-table-column
      prop="endDate"
      label="结课时间"
      width="150"
      align="center"
    />
    <el-table-column prop="subject" label="状态" width="100" align="center" />
    <el-table-column
      prop="updateTime"
      label="最后操作时间"
      width="200"
      align="center"
    />
    <el-table-column prop="" label="操作" align="center">
      <template #default="scope">
        <el-button type="primary" @click="handleEdit(scope.row.id)"
          >编辑
        </el-button>
        <el-button @click="handleDelete(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <br />
  <!-- 分页 -->
  <el-pagination
    v-model:current-page="currentPage"
    v-model:page-size="pageSize"
    :page-sizes="[10, 20, 30, 40]"
    layout="sizes, total, prev, pager, next, jumper"
    :total="total"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  />
  <!-- 添加班级 对话框 -->
  <el-dialog
    v-model="dialogFormVisible"
    :title="dialogTitle"
    width="420"
    :before-close="cancel"
  >
    <el-form
      ref="clazzFromRef"
      :model="clazz"
      label-position="left"
      label-width="80px"
      :rules="rules"
    >
      <el-form-item label="班级名称" prop="name">
        <el-input v-model="clazz.name" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="班级教室">
        <el-input v-model="clazz.room" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="开课时间" prop="beginDate">
        <el-date-picker
          v-model="clazz.beginDate"
          type="Date"
          style="width: 100%"
          placeholder="选择日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="结课时间" prop="endDate">
        <el-date-picker
          v-model="clazz.endDate"
          type="Date"
          style="width: 100%"
          placeholder="选择日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="班主任">
        <el-select v-model="clazz.masterId" placeholder="选择班主任">
          <el-option
            v-for="master in masterList"
            :key="master.id"
            :label="master.name"
            :value="master.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="学科" prop="subject">
        <el-select v-model="clazz.subject" placeholder="选择学科">
          <el-option
            v-for="subject in subjectList"
            :key="subject.value"
            :label="subject.name"
            :value="subject.value"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <!-- 对话框底部确认按钮-->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="saveClazz">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped></style>
